package com.forever.volleydemo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.forever.volleydemo.DiskLruCache.Editor;

public class DiskActivity extends Activity {
	ImageView imageView1;
	DiskLruCache mDiskLruCache = null;
	String url_pic = "http://www.baigoogledu.com/images/logo.png";

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_disk);
		imageView1 = (ImageView) findViewById(R.id.imageView1);

		/**
		 * open()方法接收四个参数， 
		 * 第一个参数指定的是数据的缓存地址， 
		 * 第二个参数指定当前应用程序的版本号
		 * 第三个参数指定同一个key可以对应多少个缓存文件，基本都是传1，
		 * 第四个参数指定最多可以缓存多少字节的数据。
		 */
		// 初始化 DiskLruCache
		try {
			File cacheDir = getDiskCacheDir(this, "bitmap");
			if (!cacheDir.exists()) {
				cacheDir.mkdirs();
			}
			mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(this), 1,
					10 * 1024 * 1024);
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 图片下载器

		DownLoadTools mDownLoadTools = DownLoadTools.getInstance(this);
		ImageLoader mmImageLoader = mDownLoadTools.getImageLoader();

		mmImageLoader.get(url_pic, new ImageListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}

			@Override
			public void onResponse(ImageContainer response, boolean isImmediate) {

				try {
					Bitmap mBitmap = response.getBitmap();

					if (mBitmap != null) {
						// MD5加密
						String key = hashKeyForDisk(url_pic);
						Editor mEditor = mDiskLruCache.edit(key);
						// 存
						OutputStream os = mEditor.newOutputStream(0);
						// 已经写入流中
						mBitmap.compress(Bitmap.CompressFormat.PNG, 100, os);

						mEditor.commit();

						// 取
						DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
						InputStream is = snapShot.getInputStream(0);
						Bitmap bitmap = BitmapFactory.decodeStream(is);
						imageView1.setImageBitmap(bitmap);
					}

				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});
	}

	/**
	 * 
	 * @param context
	 * @param uniqueName
	 *        文件分类（例如：缓存的是图片就可以命名：bimap）
	 * @return
	 */
	public File getDiskCacheDir(Context context, String uniqueName) {
		String cachePath;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable()) {
			cachePath = context.getExternalCacheDir().getPath();
		} else {
			cachePath = context.getCacheDir().getPath();
		}
		return new File(cachePath + File.separator + uniqueName);
	}

	/**
	 * 获取到当前应用程序的版本号：
	 * @param context
	 * @return
	 */
	public int getAppVersion(Context context) {
		try {
			PackageInfo info = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 1;
	}

	/**
	 * 将字符串进行MD5编码，代码如下所示：
	 * @param key
	 * @return
	 */
	public String hashKeyForDisk(String key) {
		String cacheKey;
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(key.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(key.hashCode());
		}
		return cacheKey;
	}

	private String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}

}
